<template>
  <div>
    <!-- 角色管理 -->
    <el-card shadow="never" class="margin-30" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button type="primary" size="small" @click="doAddRole">新增角色</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="AllRolesList"
        border
        stripe
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column label="#" type="index" width="60" align="center" />
        <el-table-column prop="roleName" label="角色名称" width="250 " align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column prop="createTime" label="添加时间" width="250 " align="center" />
        <el-table-column prop="col.id" label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="success" style="margin-right: 10px;" size="mini" @click="doEditRoleItem(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="doDelRoleItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          style="margin-top: 10px; text-align: center;"
          :current-page="start"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="limit"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    </el-card>
    <!-- 新增 / 编辑 卡片 -->
    <el-dialog title="编辑角色" :visible.sync="dialogVisible" width="30%">
      <el-form ref="roleDetailItemForm" :model="roleDetailItem" :rules="rules" label-width="80px" size="small">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleDetailItem.roleName" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleDetailItem.roleCode" />
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input v-model="roleDetailItem.remark" />
        </el-form-item>
        <el-form-item label="角色描述" prop="permissionIds">
          <el-checkbox label="展开/关闭" @change="handleExpandAll" />
          <el-checkbox label="全选/取消全选" @change="handelAllselected" />
          <el-tree
            ref="refMenuList"
            :data="allMenuList"
            :props="defaultProps"
            show-checkbox
            node-key="id"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSave">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import mix from '@/mixins'
import { findRolesByPage, findRolePermissions, saveRolePermissions, updateRolePermissions, removeRole } from '@/api/userController/role'
import { findAllPermissions } from '@/api/userController/permission'
export default {
  name: 'Roles',
  mixins: [mix],
  data() {
    return {
      AllRolesList: [], // 所有角色
      roleDetailItem: { // 单独角色明细
        isDeleted: 0
      },
      dialogVisible: false,
      rules: {},
      allMenuList: [], // 全部的菜单
      defaultProps: { // 配置tree结构
        children: 'children',
        label: 'title'
      },
      // expendAll: false, // 展开所有菜单 用多选框 e 代替
      menuListIds: [], // 选中菜单id
      isAddRole: false,
      loading: true
    }
  },
  created() {
    this.getAllfindAllRolesPage()
    this.getfindAllPermissions()
  },
  mounted() {

  },

  methods: {
    // 删除角色
    async doDelRoleItem(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await removeRole(id)
        const { success, message } = res
        if (success) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getAllfindAllRolesPage()
        } else {
          this.$message.error(message)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 新增 / 编辑
    async doSave() {
      let api
      // 1.判断 新增 / 编辑
      if (this.isAddRole) {
        api = saveRolePermissions
      } else {
        api = updateRolePermissions
      }
      // 2. 规整数据
      // 获取被选择的菜单id
      this.getCheckedAll()
      this.roleDetailItem.permissionIds = this.menuListIds

      // 3. 请求数据
      const res = await api(this.roleDetailItem)
      const { success, message } = res
      if (success) {
        if (this.isAddRole) {
          this.$message.success('新增成功')
        } else {
          this.$message.success('编辑成功')
        }
      } else {
        this.$message.error(message)
      }
      this.dialogVisible = false
    },

    // 新增角色
    doAddRole() {
      // 1. 打开窗口
      this.dialogVisible = true
      this.isAddRole = true
    },

    // 编辑角色
    async doEditRoleItem(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.isAddRole = false
      // 2. 获取角色明细
      this.getFindRolePermissions(id)
    },
    // 获取所有菜单
    async getfindAllPermissions() {
      const res = await findAllPermissions()
      const { data: { menus }, success } = res
      if (success) {
        this.allMenuList = menus
      }
    },

    // 获取角色明细
    async getFindRolePermissions(id) {
      const res = await findRolePermissions(id)
      const { data: { role }, success } = res
      if (success) {
        this.roleDetailItem = role
      }
    },

    // 菜单展开与关闭
    handleExpandAll(e) {
      // console.log(this.$refs.refMenuList)
      const nodesMap = this.$refs.refMenuList.store.nodesMap
      for (const key in nodesMap) {
        const item = nodesMap[key]
        item.expanded = e
      }
    },
    // 全选与取消全选
    handelAllselected(e) {
      if (e) {
        this.getAllMenuIds(this.allMenuList)
        // 通过方法 setCheckedKey() 需要传递所有的被选择的id 需要是一个数组
        this.$refs.refMenuList.setCheckedKeys(this.menuListIds)
      } else {
        this.menuListIds = []
        this.$refs.refMenuList.setCheckedKeys(this.menuListIds)
      }
      this.roleDetailItem.permissionIds = this.menuListIds
      console.log(this.menuListIds)
    },

    // 只获取被选择的菜单id
    getCheckedAll() {
      this.menuListIds = []
      // 获取被选择的菜单id  该方法只返回被选中的的菜单数组
      const checkedAll = this.$refs.refMenuList.getCheckedNodes()
      // this.roleDetailItem.permissionIds = checkedAll
      checkedAll.forEach(item => {
        this.menuListIds.push(item.id)
      })
    },

    // 获取所有菜单id
    getAllMenuIds(allMenuList) {
      for (let i = 0; i < allMenuList.length; i++) {
        const item = allMenuList[i]
        this.menuListIds.push(item.id)
        if (item.children && item.children.length > 0) {
          // 递归深度添加
          this.getAllMenuIds(item.children)
        }
      }
    },

    // 获取角色分页列表
    async getAllfindAllRolesPage() {
      this.loading = true
      const res = await findRolesByPage(this.start, this.limit)
      console.log(res)
      const { data: { rows, total }, success } = res
      if (success) {
        this.AllRolesList = rows
        this.total = total
        this.loading = false
      }
    },

    // 分页
    handleSizeChange(val) {
      this.loading = true
      this.limit = val
      this.start = 1
      this.getAllfindAllRolesPage()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.loading = true
      this.start = val
      this.getAllfindAllRolesPage()
      // console.log(`当前页: ${val}`);
    }
  }
}
</script>

<style lang="scss" scoped></style>
